package com.thesis.project.service;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.thesis.project.domain.Datatype;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Service for processing Algorithm
 * 
 */
@Service("datatypeService")
@Transactional
public class DatatypeService {

	protected static Logger logger = Logger.getLogger("service");
	
	@Resource(name="sessionFactory")
	private SessionFactory sessionFactory;
	
	/**
	 * Retrieves all persons
	 * 
	 * @return a list of persons
	 */
	public List<Datatype> getAll() {
		logger.debug("Retrieving all datatypes");
		
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Create a Hibernate query (HQL)
		Query query = session.createQuery("FROM  Datatype");
		
		// Retrieve all
		return  query.list();
	}
	
	/**
	 * Retrieves a single algorithm
	 */
	public Datatype get( Integer id ) {
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Retrieve existing person first
		Datatype datatype = (Datatype) session.get(Datatype.class, id);
		
		return datatype;
	}
	/**
	 * Adds a new algorithm
	 */
	public void add(Datatype datatype) {
		logger.debug("Adding new datatype");
		
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Save
		session.save(datatype);
	}
	
	/**
	 * Deletes an existing algorithm
	 * @param id the id of the existing algorithm
	 */
	public void delete(Integer id) {
		logger.debug("Deleting existing datatype");
		
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Retrieve existing person first
		Datatype datatype	 = (Datatype) session.get(Datatype.class, id);
		
		// Delete 
		session.delete(datatype);
	}
	
	/**
	 * Edits an existing person
	 */
	public void edit(Datatype datatype) {
		logger.debug("Editing existing datatype");
		
		// Retrieve session from Hibernate
		Session session = sessionFactory.getCurrentSession();
		
		// Retrieve existing algorithm via id
		Datatype existingDatatype = (Datatype) session.get(Datatype.class, datatype.getId());
		
		// Assign updated values to this algorithm
		existingDatatype.setId(datatype.getId());
		existingDatatype.setDataTypeName(datatype.getDataTypeName());
		existingDatatype.setDataDescription(datatype.getDataDescription());
		existingDatatype.setClassName(datatype.getClassName());


		// Save updates
		session.save(existingDatatype);
	}
}
